package handler

import (
	"EventsApp/pkg/handler/types"
  f "EventsApp/pkg/handler/helperFunctions"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"gorm.io/gorm"
)

func signUp(c *gin.Context, db *gorm.DB) {
	var user types.User

	if err := c.BindJSON(&user); err != nil {
		newErrorResponse(c, http.StatusBadRequest, err.Error())
		return
	}
	if err := checkPassword(user.Password); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})

		return
	}
	if err := checkNickname(user.Nickname); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})

		return
	}

	nick := db.First(&user, "nickname = ?", user.Nickname)

	if err := isNicknameUnique(nick); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})

		return
	}

	hashedPassword, err := f.HashPassword(user.Password)

	if err != nil {
		log.Fatalf("Error while hashing: %s", err.Error())
	}
  
	userId := uuid.New().String()

	user = types.User{Id: userId, Nickname: user.Nickname, Password: hashedPassword}

	db.Select("id", "nickname", "password").Create(&user)

	c.JSON(http.StatusCreated, gin.H{"userID": user.Id})
}

func signIn(c *gin.Context, db *gorm.DB) {
  var user types.User
  var userSignIn types.UserSignIn

	if err := c.BindJSON(&userSignIn); err != nil {
		newErrorResponse(c, http.StatusBadRequest, err.Error())
		return
	}

  oneUser := db.First(&user, "nickname = ?", userSignIn.Nickname)

  if oneUser.RowsAffected == 0 {
    return
  }

  if err := f.DecryptPassword(user.Password, userSignIn.Password); err != nil {
    c.JSON(http.StatusBadRequest, gin.H{"error %s": err.Error()})

		return
  }

  token, err := f.GenerateToken(user.Id)

  if err != nil {
    log.Fatalf("Tocken generation error: %s", err.Error())
  }

  c.JSON(http.StatusCreated, gin.H{"token": token})
}

